package com.yncmcc.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Optional;

/**
 * Created by CMCC-Sunmo on 2016/9/27.
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("userId");
        Object adminObj = session.getAttribute("adminId");
        String actionUrl = request.getRequestURL().toString();

        if(actionUrl.indexOf("/user/login")>0){
            return true;
        }

        if(actionUrl.indexOf("/user/logout")>0){
            return true;
        }

        if(userObj==null && adminObj==null){
//            request.getRequestDispatcher("login.jsp").forward(request,response);
//            response.sendRedirect("http://localhost:8080/login.jsp");
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }else if(userObj==null && adminObj!=null){
            response.sendRedirect(request.getContextPath()+"/admin/AdminSelf.jsp");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.print("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.print("afterCompletion");
    }
}
